#include "initWindow.hpp"
#include <QFile>
#include <QGraphicsDropShadowEffect>
#include <QLabel>
#include <QScreen> // 添加屏幕尺寸头文件

initWindow::initWindow(QWidget *parent)
    : QMainWindow(parent), adminGUI(nullptr) {
  // 设置窗口属性
  setAttribute(Qt::WA_TranslucentBackground, false);
  setWindowTitle("AI 智能问答");

  // 创建中央窗口部件
  QWidget *centralWidget = new QWidget(this);
  centralWidget->setObjectName("centralWidget");
  setCentralWidget(centralWidget);

  // 创建标题和副标题
  titleLabel = new QLabel("Deepseek 天下第一", centralWidget);
  titleLabel->setObjectName("titleLabel");
  titleLabel->setAlignment(Qt::AlignCenter);
  titleLabel->setStyleSheet(titleLabel->styleSheet() +
                            "font-size: 72px;"); 

  subtitleLabel = new QLabel("Reading and writing.", centralWidget);
  subtitleLabel->setObjectName("subtitleLabel");
  subtitleLabel->setAlignment(Qt::AlignCenter);
  subtitleLabel->setStyleSheet(subtitleLabel->styleSheet() +
                               "font-size: 46px;"); 

  // 为标题添加阴影效果
  QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
  shadowEffect->setOffset(1, 1);
  shadowEffect->setColor(QColor(100, 100, 100, 150));
  shadowEffect->setBlurRadius(5);
  titleLabel->setGraphicsEffect(shadowEffect);

  // 创建按钮
  userButton = new QPushButton("用户入口", centralWidget);
  userButton->setObjectName("userButton");
  userButton->setMinimumSize(180, 50); // 增大按钮尺寸
  adminButton = new QPushButton("管理员登录", centralWidget);
  adminButton->setObjectName("adminButton");
  adminButton->setMinimumSize(180, 50); // 增大按钮尺寸

  // 添加按钮图标
  QPixmap favicon(":/resource/A4theme/A4-favicon.png");
  if (!favicon.isNull()) {
    userButton->setIcon(QIcon(favicon));
    userButton->setIconSize(QSize(30, 30)); // 增大图标尺寸
    adminButton->setIcon(QIcon(favicon));
    adminButton->setIconSize(QSize(30, 30)); // 增大图标尺寸
  }

  // 创建页脚
  QLabel *footerLabel = new QLabel("© 2024", centralWidget);
  footerLabel->setObjectName("footerLabel");
  footerLabel->setAlignment(Qt::AlignCenter);

  // 创建A4纸特有的装饰元素 - 页码指示
  QLabel *pageIndicator = new QLabel("- 1 -", centralWidget);
  pageIndicator->setObjectName("pageIndicator");
  pageIndicator->setAlignment(Qt::AlignCenter);
  pageIndicator->setStyleSheet(
      "font-size: 24px; color: #aaa; margin-top: 10px;");

  // 创建A4纸特有的装饰元素 - 页眉
  QLabel *headerLabel = new QLabel("A4 Theme", centralWidget);
  headerLabel->setObjectName("headerLabel");
  headerLabel->setAlignment(Qt::AlignRight);
  headerLabel->setStyleSheet(
      "font-size: 20px; color: #aaa; margin-bottom: 10px;");

  // 布局
  QVBoxLayout *layout = new QVBoxLayout(centralWidget);
  layout->addWidget(headerLabel);
  layout->addWidget(titleLabel);
  layout->addWidget(subtitleLabel);
  layout->addSpacing(80); // 增大间距
  layout->addWidget(userButton, 0, Qt::AlignHCenter);
  layout->addSpacing(30); // 增大按钮之间的距离
  layout->addWidget(adminButton, 0, Qt::AlignHCenter);
  layout->addSpacing(60); // 增大间距
  layout->addWidget(footerLabel);
  layout->addWidget(pageIndicator);
  layout->setContentsMargins(60, 60, 60, 60); // 增大边距
  centralWidget->setLayout(layout);

  // 加载QSS样式
  QFile styleFile(":/resource/A4theme/a4style.qss");
  if (styleFile.open(QFile::ReadOnly | QFile::Text)) {
    QString styleSheet = QString::fromUtf8(styleFile.readAll());
    this->setStyleSheet(styleSheet);
    styleFile.close();
  } else {
    qDebug() << "无法打开样式文件:" << styleFile.errorString();
  }

  // 为按钮安装事件过滤器，添加悬停效果
  userButton->installEventFilter(this);
  adminButton->installEventFilter(this);

  // 创建标题动画 - 平滑进入
  titleAnimation = new QPropertyAnimation(titleLabel, "geometry");
  titleAnimation->setDuration(800);
  titleAnimation->setStartValue(
      QRect(titleLabel->x(), -30, titleLabel->width(), titleLabel->height()));
  titleAnimation->setEndValue(titleLabel->geometry());
  titleAnimation->setEasingCurve(QEasingCurve::OutQuad);
  titleAnimation->start();

  // 使用定时器延迟加载子标题
  animationTimer = new QTimer(this);
  animationTimer->setSingleShot(true);
  connect(animationTimer, &QTimer::timeout, [this]() {
    QPropertyAnimation *subAnimation =
        new QPropertyAnimation(subtitleLabel, "opacity");
    subAnimation->setDuration(800);
    subAnimation->setStartValue(0.0);
    subAnimation->setEndValue(1.0);
    subAnimation->start(QPropertyAnimation::DeleteWhenStopped);
  });
  animationTimer->start(600);

  // 设置子标题透明度为0，等待动画显示
  QGraphicsOpacityEffect *opacityEffect =
      new QGraphicsOpacityEffect(subtitleLabel);
  opacityEffect->setOpacity(0);
  subtitleLabel->setGraphicsEffect(opacityEffect);

  // 获取屏幕尺寸
  QScreen *screen = QGuiApplication::primaryScreen();
  QRect screenGeometry = screen->geometry();
  int screenHeight = screenGeometry.height();
  int screenWidth = screenGeometry.width();

  // 计算窗口大小 - 使用屏幕高度的80%和保持A4纸的宽高比 (1:√2)
  int height = static_cast<int>(screenHeight * 0.8);
  int width = static_cast<int>(height / 1.414); // A4纸的宽高比约为1:1.414

  // 确保宽度不超过屏幕宽度的70%
  if (width > screenWidth * 0.7) {
    width = static_cast<int>(screenWidth * 0.7);
    height = static_cast<int>(width * 1.414);
  }

  this->resize(width, height);

  // 窗口居中显示
  this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter,
                                        this->size(), screenGeometry));

  connect(userButton, &QPushButton::clicked, this,
          &initWindow::onUserButtonClicked);
  connect(adminButton, &QPushButton::clicked, this,
          &initWindow::onAdminButtonClicked);
}

void initWindow::paintEvent(QPaintEvent *event) {
  QMainWindow::paintEvent(event);

  // A4 主题模拟真实纸张效果
  QPainter painter(this);

  // 设置纸张背景色
  painter.fillRect(rect(), QColor(252, 252, 252));

  // 轻微的纸张纹理
  painter.setPen(QPen(QColor(240, 240, 240)));

  // 随机轻微的纹理点
  for (int i = 0; i < width(); i += 10) {
    for (int j = 0; j < height(); j += 10) {
      // 只绘制一部分点，创建随机的纸张效果
      if ((i + j) % 7 == 0) {
        painter.drawPoint(i, j);
      }
    }
  }

  // 绘制淡淡的纸张边缘阴影
  QLinearGradient topShadow(0, 0, 0, 10);
  topShadow.setColorAt(0, QColor(220, 220, 220, 30));
  topShadow.setColorAt(1, QColor(255, 255, 255, 0));
  painter.fillRect(0, 0, width(), 10, topShadow);

  QLinearGradient leftShadow(0, 0, 10, 0);
  leftShadow.setColorAt(0, QColor(220, 220, 220, 30));
  leftShadow.setColorAt(1, QColor(255, 255, 255, 0));
  painter.fillRect(0, 0, 10, height(), leftShadow);
}

void initWindow::onUserButtonClicked() {
  LoginWindow *loginWindow = new LoginWindow();
  loginWindow->setAttribute(Qt::WA_DeleteOnClose);
  loginWindow->setWindowTitle("用户登录");
  loginWindow->show();
  this->close();
}

void initWindow::onAdminButtonClicked() {
  // 创建管理员界面
  if (!adminGUI) {
    adminGUI = new AdminLogin();
    adminGUI->setAttribute(Qt::WA_DeleteOnClose);
    // 当管理界面关闭时，将指针设为nullptr
    connect(adminGUI, &QObject::destroyed, [this]() { adminGUI = nullptr; });
  }

  adminGUI->show();

  this->close();
}

// 按钮悬停效果的事件过滤器
bool initWindow::eventFilter(QObject *watched, QEvent *event) {
  if (watched == userButton || watched == adminButton) {
    if (event->type() == QEvent::Enter) {
      QPushButton *button = qobject_cast<QPushButton *>(watched);

      // 不改变按钮大小，只添加边框和阴影效果
      QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect;
      shadowEffect->setBlurRadius(8); 
      shadowEffect->setColor(QColor(0, 0, 0, 60)); 
      shadowEffect->setOffset(1, 1);               
      button->setGraphicsEffect(shadowEffect);

      // 改变按钮边框颜色
      button->setStyleSheet(button->styleSheet() +
                            "QPushButton { border: 2px solid #04077e; }");

      return true;
    } else if (event->type() == QEvent::Leave) {
      // 鼠标离开按钮区域
      QPushButton *button = qobject_cast<QPushButton *>(watched);

      // 恢复原始样式
      button->setGraphicsEffect(nullptr);

      // 重置边框样式
      button->setStyleSheet(
          button->styleSheet().replace("border: 2px solid #04077e;", ""));

      return true;
    }
  }
  return QMainWindow::eventFilter(watched, event);
}